var router = require('koa-router')();
import asyncBusboy from 'async-busboy';
import fs from 'fs';
import path from "path";
var ffmpeg = require('ffmpeg');

const {exec,execSync} = require('child_process');


router.post('/file/upload',async (ctx, next) =>{
	const {files, fields} = await asyncBusboy(ctx.req);

	let {name,file_path,output_path} = uploadFile(files[0]);
    let audio = await getDuration(file_path);
	let outputname = path.join(output_path , `/${name}`)
	let covert = `ffmpeg -i ${file_path} -c:a libmp3lame -b:a 128k -map 0:0 -f segment -segment_time 10 -segment_list ${outputname}.m3u8 -segment_format mpegts ${outputname}_%03d.ts`
	execSync(covert);
	execSync(`cd ${output_path} && zip ../${name}.zip -r * `)
	execSync(`rm -rf ${output_path} && rm -rf ${file_path}`)
	ctx.body = {
        duration:JSON.stringify(audio.metadata.duration),
        path:"/m3u8/" + name+".zip"
    }
});



function uploadFile(file){
    var filePath = file.path,
    content = fs.readFileSync(filePath),
	file_path = "",
    filename = file.filename||file.name;

    var nonce_str =uuid(),
        dirname = `/${nonce_str}`+filename.match(/.(\w+)$/)[0];
    file_path = path.join(__dirname , "../../../mp3");
    
    if(!fs.existsSync(file_path)){
        fs.mkdirSync(file_path);
    }
    let output_path = path.join(file_path , "/" ,nonce_str)
    fs.mkdirSync(output_path)
    file_path += dirname;
    fs.writeFileSync(file_path, content);

    return {
    	name:nonce_str,
    	file_path,
    	output_path
    };
}


async function getDuration(filePath){
    return  new ffmpeg(filePath);
}

function uuid(){
	return Math.random().toString(36).slice(2)
}



export default router;
